package com.github.ylt.protocol.ssdp;

import com.github.ylt.conf.Configure;
import com.github.ylt.utils.IpUtils;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

public class Protocol {

    private final String[] searchList = new String[]{"upnp:rootdevice","urn:schemas-upnp-org:device:MediaServer:1","urn:schemas-upnp-org:device:MediaRenderer:1","urn:schemas-upnp-org:service:AVTransport:1","urn:dial-multiscreen-org:service:dial:1"};
    private String protocolLine = "";
    private final String Host = Configure.DEFAULT_MULTICAST_ADDRESS+":"+Configure.DEFAULT_MULTICAST_PORT;
    private final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US).withZone(ZoneId.of("GMT"));
    private Map<String,String> map = new HashMap<>();
    private final String location = "http://"+ IpUtils.getInstance().localhostIpv4()+":33854/description.xml";

    public Protocol() {}

    public String getProtocolLine() {
        return protocolLine;
    }

    public void parse(String message) {
        String[] split = message.trim().split("\r\n");
        protocolLine = split[0];
       for (int i = 1; i < split.length; i++) {
           String[] split1 = split[i].trim().split(":");
           map.put(split1[0], split1[1]);
       }
    }

    public String builderSearch(int count){
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("M-SEARCH * HTTP/1.1").append("\r\n");
        stringBuilder.append("HOST: ").append(Host).append("\r\n");
        stringBuilder.append("MAN: \"ssdp:discover\"").append("\r\n");
        stringBuilder.append("MX: 5").append("\r\n");
        stringBuilder.append(searchList[count]).append("\r\n");
        return stringBuilder.toString();
    }

    public String builderResponse(){
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("HTTP/1.1 200 OK").append("\r\n");
        stringBuilder.append("CACHE-CONTROL: max-age=66").append("\r\n");
        stringBuilder.append("USN: ").append(Configure.UDN).append("::").append(this.map.get("ST")).append("\r\n");
        stringBuilder.append("EXT: ").append("\r\n");
        stringBuilder.append("LOCATION: ").append(location).append("\r\n");
        stringBuilder.append("Date: ").append(FORMATTER.format(LocalDateTime.now())).append("\r\n");
        stringBuilder.append("ST: ").append(map.get("ST")).append("\r\n");
        return stringBuilder.toString();
    }

    public String buildActiveNotifications(){
        return "";
    }



}
